package com.github.maojx0630.translate;

import cn.hutool.core.util.ReflectUtil;
import com.github.maojx0630.translate.cache.ClassCacheDto;
import com.github.maojx0630.translate.cache.ClassFieldCache;
import com.github.maojx0630.translate.translate.TranslateHandle;

import java.lang.annotation.Annotation;
import java.util.List;

/**
 * @author 毛家兴
 * @since 2024-01-31 14:35
 */
public class TranslateUtil {

    private final ClassFieldCache classFieldCache;

    public TranslateUtil(ClassFieldCache classFieldCache) {
        this.classFieldCache = classFieldCache;
    }

    public <T> T translate(T o) {
        if (o instanceof Iterable<?> iterable) {
            for (Object object : iterable) {
                translate(object);
            }
        } else {
            List<ClassCacheDto<?>> list = classFieldCache.getClassField(o);
            for (ClassCacheDto<? extends Annotation> dto : list) {
                Object fieldValue = ReflectUtil.getFieldValue(o, dto.getField());
                if (null == fieldValue) {
                    continue;
                }
                if (fieldValue instanceof String string) {
                    setValue(dto, string, o);
                }
            }
        }
        return o;
    }

    private <A extends Annotation> void setValue(ClassCacheDto<A> dto, String string, Object obj) {
        TranslateHandle<A> translateHandle = dto.getTranslateHandle();
        A translateField = dto.getTranslateField();
        Object translateValue =
                translateHandle.getTranslateValue(translateField, string, dto.getField());
        for (String name : translateHandle.getTranslateField(translateField, string, dto.getField())) {
            ReflectUtil.setFieldValue(obj, name, translateValue);
        }
    }
}
